package com.soyuan.util;

import com.mongodb.Block;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoClientOptions.*;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by twx on 2017/10/24.
 */
public class MongoUtil {
    private static final Logger logger = LoggerFactory.getLogger(MongoUtil.class);
    private static MongoClient client;
    private static MongoDatabase testDB;

    public static MongoClient getClient() {
        if (client==null)
            return new MongoClient("localhost", 27017);
        return client;
    }

    public static MongoDatabase getDB(){
        if (testDB==null){
            testDB = getClient().getDatabase("test");
            //logger.info("已连接到mongoDB,成功获取test库");
        }
        return testDB;
    }

    public static void close() {
        getClient().close();
    }

    public static MongoCollection<Document> getCollection(String collectionName){
        return getDB().getCollection(collectionName);
    }

    public static boolean connMongo() {
        boolean status=false;
        MongoClientOptions build = MongoClientOptions.builder().build();
        MongoClient mongo = new MongoClient("localhost:27017",build);
        try {
            mongo.getAddress();
            status = true;
            logger.info("已成功连接mongodb");
        } catch (Exception e) {
            logger.error("连接Mongo服务器失败--->"+e.getCause());
            mongo.close();
        }
        return status;
    }

    public static void main(String[] args) {
        boolean b = connMongo();
        System.out.println(b);
    }

}
